// pages/other/other.js
Page({
    data: {
      goodsList: [],
      loading: true,
      filterType: 'all',
      searchKey: '',
      page: 1,
      pageSize: 10,
      total: 0
    },
  
    onLoad: function() {
      this.fetchGoodsList();
    },
  
    onShow: function() {
      // 页面显示时重新获取数据（可选）
      // this.fetchGoodsList();
    },
  
    // 获取商品列表
    fetchGoodsList: function(refresh = false) {
      if (refresh) {
        this.setData({
          page: 1,
          goodsList: []
        });
      }
      
      const { page, pageSize, filterType, searchKey } = this.data;
      this.setData({ loading: true });
      
      wx.cloud.callFunction({
        name: 'getOtherGoods',
        data: {
          page: page,
          pageSize: pageSize,
          filterType: filterType,
          searchKey: searchKey
        },
        success: (res) => {
            console.log(res);
          this.setData({ loading: false });
          if (res.result && res.result.success) {
            res.result.data.forEach(item=>{
                let arr = item.goodsImage.split(',')
                if (arr.length) {
                    item.images = arr
                }
            })
            const newGoodsList = refresh ? res.result.data : [...this.data.goodsList, ...res.result.data];
            
            this.setData({
              goodsList: newGoodsList,
              total: res.result.total || 0,
              page: page + 1
            });
          } else {
            wx.showToast({
              title: '获取商品列表失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          this.setData({ loading: false });
          console.error('调用云函数失败', err);
          wx.showToast({
            title: '网络错误，请稍后再试',
            icon: 'none'
          });
        }
      });
    },
  
    // 搜索商品
    onSearch: function(e) {
      const searchKey = e.detail || '';
      this.setData({
        searchKey: searchKey,
        page: 1,
        goodsList: []
      });
      this.fetchGoodsList();
    },
  
   
    // 防止单选框点击穿透
    preventTouch: function(e) {
      e.stopPropagation();
    },
  
    // 点击商品项
    onGoodsTap: function(e) {
      const goodsId = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/pages/goods/index?goodsId=${goodsId}`
    });
    },
  
    // 下拉刷新
    onPullDownRefresh: function() {
      this.fetchGoodsList(true).then(() => {
        wx.stopPullDownRefresh();
      });
    },
  
    // 上拉加载更多
    onReachBottom: function() {
      const { page, pageSize, goodsList, total } = this.data;
      if (goodsList.length >= total) return;
      
      this.fetchGoodsList();
    }
  });